package cn.jiangjiesheng.bootstrap.fileport.domain.base;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import cn.jiangjiesheng.bootstrap.commons.utils.ContextUtil;
import cn.jiangjiesheng.bootstrap.fileport.infrastructure.properties.FilePortProperties;
import cn.jiangjiesheng.bootstrap.fileport.infrastructure.utils.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;

import javax.annotation.PreDestroy;
import java.io.File;
import java.io.IOException;
import java.util.Objects;

/**
 * Created by dev@jiangjiesheng.cn on 2021/3/16  <br/>
 */
@Slf4j
public class EChart {

    private static ChromeDriverService service;

    private WebDriver driver;

    private void startService() {
        FilePortProperties filePortProperties = ContextUtil.getBean(FilePortProperties.class);
        log.info("using chrome webdriver version {}", filePortProperties.getChromeWebdriverPath());
        service = new ChromeDriverService.Builder()
                .usingDriverExecutable(new File(filePortProperties.getChromeWebdriverPath()))
                .usingAnyFreePort()
                .build();
        try {
            service.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 渲染为Base64
     *
     * @param options
     * @return byte[]
     */
    public EChart(final JsonNode options, int width, int height) {
        // 关闭动画效果
        ((ObjectNode) options).put("animation", false);
        if (Objects.isNull(driver)) {
            log.info("init chrome webdriver ...");
            this.startService();
            ChromeOptions chromeOptions = new ChromeOptions();
            chromeOptions.addArguments("window-size=800,800", "--headless", "--disable-gpu");
            driver = new ChromeDriver(service, chromeOptions);
        }
        String htmlContent = FileUtils.readStringFromResource("templates/echarts.html");

        htmlContent = htmlContent
                .replace("#{chartOptions}", options.toPrettyString())
                .replace("#{height}", String.valueOf(height))
                .replace("#{width}", String.valueOf(width));
        try {
            driver.get("data:text/html;charset=utf-8," + htmlContent);
        } finally {
        }
    }

    public String toBase64() {
        return this.driver.findElement(By.id("container")).getScreenshotAs(OutputType.BASE64);
    }

    public byte[] toBytes() {
        return this.driver.findElement(By.id("container")).getScreenshotAs(OutputType.BYTES);
    }

    @PreDestroy
    public void destroy() {
        driver.quit();
    }

}
